﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//
using CommonClass;
using System.Diagnostics;
using EncryptProject;
using SoftKeyLib;
using CommonBase;
using SurveillanceLib;


namespace BindingKeyProject
{
    public partial class frm_Main : Form
    {
        #region 常量

        const int CODE_SPLIT_LENGTH = 5; // 用户代码串包含几个部分
        const int CPU_LENGTH = 16; // CPU 字符串长度
        const int DISK_LENGTH = 8; // 磁盘字符串长度

        #endregion

        #region 变量

        SoftKeyOperation keyOperation = new SoftKeyOperation();
        string cpuID; // CPU 序号
        string diskID; // 磁盘序号
        string projGUID; // 项目 ID
        string mNum; // 用户机器码
        string md5; // MD5 值（对公司）
        string mTime; // 首次查看注册码时间

        #endregion

        #region 构造函数

        public frm_Main()
        {
            InitializeComponent();
        }

        #endregion

        #region 事件

        /// <summary>
        /// 退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit(); // 退出程序
        }

        /// <summary>
        /// 粘贴
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPaste_Click(object sender, EventArgs e)
        {
            btnAnalyze.Enabled = btnBindingKey.Enabled = false;

            tbRegCode.SelectAll();
            tbRegCode.Paste();
            tbRegCode.Text = tbRegCode.Text.Replace("\r\n", string.Empty).Replace('\n', ' ').Replace('\r', ' ').Trim();
        }

        /// <summary>
        /// 文本框内容改变时，即：有内容时按钮可用；反之亦然！
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbRegCode_TextChanged(object sender, EventArgs e)
        {
            btnAnalyze.Enabled = false;

            if (!string.IsNullOrWhiteSpace(tbRegCode.Text) && tbRegCode.Text.Contains(' ') &&
                tbRegCode.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length == CODE_SPLIT_LENGTH) // 分解用户代码串
            {
                btnAnalyze.Enabled = true;
            }
        }

        /// <summary>
        /// 分析用户代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAnalyze_Click(object sender, EventArgs e)
        {
            btnBindingKey.Enabled = false;
            string[] userCodes = tbRegCode.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // 分解用户代码
            Guid outGUID;

            if (userCodes != null && userCodes.Length == CODE_SPLIT_LENGTH &&
                userCodes[0].Length == CPU_LENGTH &&
                userCodes[1].Length == DISK_LENGTH &&
                userCodes[2].Length > 0 &&
                userCodes[3].Length == SoftKeyOperation.KEYSTRING_LENGTH &&
                Guid.TryParse(userCodes[4], out outGUID))
            {
                try
                {
                    string mendTime = EncryptAlgorithmHelper.Decrypt(userCodes[2]); // 解析用户首次查看注册码时间
                    string strMNum = (userCodes[0] + userCodes[1]).Substring(0, 24); // 获得 24 位 CPU 和硬盘序列号，并从中取出前 24 个字符作为机器码
                    string companyMD5 = EncryptAlgorithmHelper.MD5Hash(string.Format(SoftKeyOperation.MD5_FORMAT_STYLE4COMPANY,
                        strMNum, mendTime, userCodes[4])); // MD5（对公司）

                    if (companyMD5.Equals(userCodes[3])) // 判断用户传入的信息的正确性
                    {
                        cpuID = userCodes[0];
                        diskID = userCodes[1];
                        mNum = strMNum;
                        mTime = mendTime;
                        md5 = userCodes[3];
                        projGUID = userCodes[4];

                        btnBindingKey.Enabled = true;
                    }
                    else
                        MessageBox.Show("MD5 不匹配！", ConstantString.MSG_COMPANY);
                }
                catch (System.Exception ex)
                {
#if DEBUG
                    Debug.WriteLine(ex.Message);
#endif
                    MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
                }
            }
            else
            {
                MessageBox.Show("用户代码不正确！", ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 绑定加密锁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBindingKey_Click(object sender, EventArgs e)
        {
            #region 验证
            if (string.IsNullOrWhiteSpace(tbUser.Text.Trim()))
            {
                MessageBox.Show("请输入该用户的信息！", ConstantString.MSG_COMPANY);
                return;
            }

            if (string.IsNullOrWhiteSpace(md5))
            {
                MessageBox.Show("用户注册码不正确！", ConstantString.MSG_COMPANY);
                return;
            }

            if (string.IsNullOrWhiteSpace(mNum))
            {
                MessageBox.Show("用户机器码不正确！", ConstantString.MSG_COMPANY);
                return;
            }

            if (string.IsNullOrWhiteSpace(mTime))
            {
                MessageBox.Show("首次查看注册码时间不正确！", ConstantString.MSG_COMPANY);
                return;
            }
            #endregion

            if (keyOperation.EasyFindSoftKey(this.Handle) &&
                keyOperation.FindSoftKeyPro()) // 多方式判断系统中是否存在着加密锁，并且只能是新锁
            {
                if (MessageBox.Show("确定要绑定加密锁吗？注：该操作不可逆！", ConstantString.MSG_COMPANY, MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button1,
                    MessageBoxOptions.DefaultDesktopOnly) == DialogResult.Yes)
                {
                    bool isBindingKeySuccess = Utilities.CheckSoftKey4BindingKey(this.Handle, md5, keyOperation); // 绑定加密锁

                    if (isBindingKeySuccess) // 成功绑定加密锁时
                    {
                        SurveillanceDAL dataOperation = new SurveillanceDAL();
                        int addUserCount = dataOperation.AddUserItem(tbUser.Text.Trim(), 
                            cpuID, diskID, md5, projGUID, 
                            keyOperation.GetChipID(),
                            mNum, mTime, DateTime.Now.ToString()); // 将用户信息写入数据库中

                        if (addUserCount > 0)
                            MessageBox.Show("成功绑定加密锁并正确入库！", ConstantString.MSG_COMPANY);
                        else
                            MessageBox.Show("成功绑定加密锁但入库失败！", ConstantString.MSG_COMPANY, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    //Application.Exit(); // 退出程序
                }
            }
            else if (!keyOperation.EasyFindSoftKey(this.Handle)) // 未找到加密锁
            {
                MessageBox.Show(string.Format(Utilities.ERROR_INFORMATION_STYLE,
                        (int)SoftKeyErrorEnum.CannotFindSoftKey,
                        Utilities.GetEnumDisplayDescription(SoftKeyErrorEnum.CannotFindSoftKey)),
                        ConstantString.MSG_COMPANY);
            }
            else // 数据不正确
            {
                MessageBox.Show(string.Format(Utilities.ERROR_INFORMATION_STYLE,
                        (int)SoftKeyErrorEnum.WrongDataInSoftKey,
                        Utilities.GetEnumDisplayDescription(SoftKeyErrorEnum.WrongDataInSoftKey)),
                        ConstantString.MSG_COMPANY);
            }
        }

        #endregion

        #region Override

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case Win32.WM_DEVICECHANGE:
                    keyOperation.OnDeviceChange(ref m, true);
                    break;
            }

            base.WndProc(ref m);
        }

        #endregion
    }
}
